package cn.com.ourclass.webviewnew.wb;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.hc.framework.mode.BaseActivity;
import com.hc.framework.titlebar.CommonTitleBar;
import com.hc.framework.utils.NetUtil;
import com.hc.framework.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.ourclass.webviewnew.R;
import cn.com.ourclass.webviewnew.wb.config.FullscreenHolder;
import cn.com.ourclass.webviewnew.wb.config.IWebPageView;
import cn.com.ourclass.webviewnew.wb.config.MyWebChromeClient;
import cn.com.ourclass.webviewnew.wb.config.MyWebViewClient;
import cn.com.ourclass.webviewnew.wb.js.MiniwebInterface;
import cn.com.ourclass.webviewnew.web.tools.PhotoSelectActivity;
import qiu.niorgai.StatusBarCompat;



/**
 * 网页可以处理:
 * 点击相应控件:拨打电话、发送短信、发送邮件、上传图片、播放视频
 * 进度条、返回网页上一层、显示网页标题
 */
public class WebViewActivity extends BaseActivity implements IWebPageView {

    // 进度条
    ProgressBar mProgressBar;
    WebView webView;
    // 全屏时视频加载view
    FrameLayout videoFullView;

    // 网页是否加载完成
    public boolean mPageFinish;
    // 加载视频相关
    private MyWebChromeClient mWebChromeClient;
    //是否需要分享
    // 网页链接
    public String mUrl;
    //是否需要头部
    private boolean needTitle;
    private String statusBarColor;

    private LinearLayout shareLink;

    private String shareText = "";

    private void getIntentData() {
        if (getIntent() != null) {
            mUrl = getIntent().getStringExtra("mUrl");
            needTitle = getIntent().getBooleanExtra("needTitle", true);
            statusBarColor = getIntent().getStringExtra("statusBarColor");
            if(statusBarColor.equals("")){
                statusBarColor = "#333333";
            }
        }
    }

    private static List<Activity> lists = new ArrayList<>();


    @Override
    public void showWebView() {
        webView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hindWebView() {
        webView.setVisibility(View.INVISIBLE);
    }

    @Override
    public void fullViewAddView(View view) {
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        videoFullView = new FullscreenHolder(WebViewActivity.this);
        videoFullView.addView(view);
        decor.addView(videoFullView);
    }

    @Override
    public void showVideoFullView() {
        videoFullView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hindVideoFullView() {
        videoFullView.setVisibility(View.GONE);
    }


    @Override
    public void addImageClickListener() {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\");" +
                "var imgs = \"\";" +
                "for(var i=0;i<objs.length;i++){" +
                "var obj = objs[i];" +
                "imgs += obj.getAttribute(\"src\")+\"#_#\";" +
                "}" +
                "for(var i=0;i<objs.length;i++){" +
                "objs[i].onclick=function(){" +
                "window.miniweb.imageClick(imgs,this.getAttribute(\"src\"));" +
                "}" +
                "}" +
                "})()");
    }



    public FrameLayout getVideoFullView() {
        return videoFullView;
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 上传图片之后的回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MyWebChromeClient.FILECHOOSER_RESULTCODE) {
            mWebChromeClient.mUploadMessage(data, resultCode);
        } else if (requestCode == MyWebChromeClient.FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            mWebChromeClient.mUploadMessageForAndroid5(data, resultCode);
        }
        super.onActivityResult(requestCode,resultCode,data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(intentResult != null) {
            if(intentResult.getContents() == null) {

            } else {
                // scanResult 为 获取到的二维码扫描的字符串
                String scanResult = intentResult.getContents();
                //Toast.makeText(this,"扫描成功"+scanResult,Toast.LENGTH_LONG).show();
                //webView.loadUrl("javascript:getScanResult(\"fadfsdfsadfdfasdfasdfadsfdasf\");");
                //webView.loadUrl("javascript:getScanResult(\""+scanResult+"\");");
                webView.loadUrl("javascript:layui.use(['jquery'],function(){" +
                        "getScanResult(\""+scanResult+"\");"+
                        "})");
            }
        } else {
            if(resultCode == RESULT_OK) {
                switch (requestCode) {
                    case PhotoSelectActivity.REQUEST_PHOTO_CODE:
                        String result = data.getStringExtra("result");
                        webView.loadUrl("javascript:layui.use(['jquery'],function(){" +
                                "getUploadResult(\""+result+"\");"+
                                "})");
                        break;
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //全屏播放退出全屏
            if (mWebChromeClient.inCustomView()) {
                hideCustomView();
                return true;

                //返回网页上一页
            } else if (webView.canGoBack()) {
                finish();
                //webView.goBack();
                return true;

                //退出网页
            } else {
                webView.loadUrl("about:blank");
                finish();
            }
        }

        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
        // 支付宝网页版在打开文章详情之后,无法点击按钮下一步
        webView.resumeTimers();
        // 设置为横屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            ViewGroup parent = (ViewGroup) webView.getParent();
            if (parent != null) {
                parent.removeView(webView);
            }
            webView.removeAllViews();
            webView.loadUrl("about:blank");
            webView.stopLoading();
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            webView.destroy();
            webView = null;
        }
    }

    @Override
    protected void initTitle(CommonTitleBar titleBar) {

    }

    @Override
    protected void initData() {
        loadWebpage();
        //去掉下拉监听
//        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
//            @Override
//            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
//                loadWebpage();
//            }
//
//            @Override
//            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
//                //load more refreshing...
//            }
//        });

        //materialRefreshLayout.finishRefresh();
        //materialRefreshLayout.finishRefreshLoadMore();
    }

    //加载网页
    public void loadWebpage(){
        if(NetUtil.getNetWorkState(this) == -1){
            ImageView nopage = (ImageView)findViewById(R.id.nonetwork);
            nopage.setVisibility(View.VISIBLE);
        }else {
            mPageFinish = false;
            webView.loadUrl(mUrl);
        }
    }

    @Override
    protected void initView() {
        LinearLayout back = (LinearLayout)findViewById(R.id.back);
        webView = (WebView)findViewById(R.id.webview_detail);
        mProgressBar = (ProgressBar)findViewById(R.id.pb_progress);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        RelativeLayout titleBar = (RelativeLayout)findViewById(R.id.action_bar);
        if(needTitle){
            titleBar.setVisibility(View.VISIBLE);
        }else{
            titleBar.setVisibility(View.GONE);
        }



        //mProgressBar.setVisibility(View.VISIBLE);
        WebSettings ws = webView.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 缩放比例 1
        webView.setInitialScale(1);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否支持多个窗口。
        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);

        mWebChromeClient = new MyWebChromeClient(this);
        webView.setWebChromeClient(mWebChromeClient);
        // 与js交互
        webView.addJavascriptInterface(new MiniwebInterface(this), "miniweb");
        webView.setWebViewClient(new MyWebViewClient(this));

    }

    @Override
    protected void setRootView() {
        getIntentData();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); //全屏
        setContentView(R.layout.activity_browser);
        setStatusBar(statusBarColor,false);

    }

    public void setTitle(String titleStr){
        TextView title = (TextView)findViewById(R.id.title);
        title.setText(StringUtil.subStringCN(titleStr,24));

    }

    //正则匹配，剔除掉uid的参数
    public String changeUrl(String url){
        String regex = "&uid=\\d+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            String uid = matcher.group(0);
            String[] arr = url.split(uid);
            url = "";
            for(int i = 0 ; i < arr.length ; i++){
                url += arr[i];
            }
            return url;
        } else {
            //System.out.println("no match");
            return url;
        }
    }

    /**
     * 打开网页:
     *
     * @param mContext 上下文
     * @param mUrl      要加载的网页url
     */
    public static void loadUrl(Context mContext, String mUrl,boolean needTitle,String statusBarColor) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("mUrl", mUrl);
        intent.putExtra("needTitle",needTitle);
        intent.putExtra("statusBarColor",statusBarColor);
        mContext.startActivity(intent);
    }

    public static void restUrl(Context mContext, String mUrl, boolean needTitle,String statusBarColor) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("mUrl", mUrl);
        intent.putExtra("statusBarColor",statusBarColor);
        intent.putExtra("needTitle",needTitle);
        mContext.startActivity(intent);
        Activity activity = (Activity)mContext;
        activity.finish();
    }

   public void close(){
       finish();
   }

    /*
    public static void gohome(Context mContext) {
        Intent intent = new Intent(mContext, MainActivity.class);
        mContext.startActivity(intent);

        ActiviyController.finishAll();
    }
    */

    public void setStatusBar( String colorStr, boolean isHide) {
        //修改状态栏颜色
        StatusBarCompat.setStatusBarColor(this, Color.parseColor(colorStr));
        if(isHide){
            StatusBarCompat.translucentStatusBar(this);
        }

    }
}